<?php

namespace app\models;

use think\Db;
use think\Model;

class Userstatus extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $defaultSoftDelete = 0;


    /**
     * 待单状态变更
     * @return void
     */
    public static function UserStatus_m($user_id, $type, $orderid, $status, $lat = 0, $lng = 0, $address = "")
    {

        if ($orderid == 0 || $type == 2) {
            (new Userstatus())->allowfield(true)->save(['type' => $type, 'user_id' => $user_id, 'status' => $status, 'orderid' => $orderid, 'created' => date('Y-m-d H:i:s'), 'lat' => $lat, 'lng' => $lng, 'address' => $address]);
        } elseif ($orderid > 0 && $type == 1) {
            $order = (new Userstatus())->where(['orderid' => $orderid, 'user_id' => $user_id, 'type' => 2])->find();
            if (!empty($order)) {
                (new Userstatus())->allowfield(true)->save(['type' => 1], ['id' => $order['id']]);
            } else {
                (new Userstatus())->allowfield(true)->save(['type' => $type, 'user_id' => $user_id, 'status' => $status, 'orderid' => $orderid, 'created' => date('Y-m-d H:i:s'), 'lat' => $lat, 'lng' => $lng, 'address' => $address]);
            }
        }
        $userstatus =  (new Userstatus())->order('id desc')->where(['type' => 2, 'user_id' => $user_id])->value('status') ?? 2;
        (new User())->where('id', $user_id)->update(['status' => $userstatus, 'address' => $address]);
    }
}
